<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      size="small"
      :inline="true"
      v-show="showSearch"
      label-width="88px"
    >
      <el-form-item label="所属部门" prop="deptId">
        <!-- <el-input
          v-model="queryParams.deptId"
          placeholder="请输入所属部门"
          clearable
          @keyup.enter.native="handleQuery"
        /> -->
        <el-cascader
          v-model="queryParams.deptId"
          :options="deptOptions"
          @change="handleChange"
          placeholder="请选择所属部门"
        >
        </el-cascader>
        <!-- <el-select
          v-model="queryParams.deptId"
          placeholder="请选择所属部门"
          clearable
        >
          <el-option
            v-for="item in deptList"
            :key="item.deptId"
            :label="item.deptName"
            :value="item.deptId"
          />
          
        </el-select> -->
      </el-form-item>
      <el-form-item label="小区名称" prop="community">
        <!-- <el-input
          v-model="queryParams.community"
          placeholder="请输入小区名称"
          clearable
          @keyup.enter.native="handleQuery"
        /> -->
        <el-select
          v-model="queryParams.community"
          placeholder="请先选择所属部门"
          clearable
        >
          <el-option
            v-for="item in communityOptions"
            :key="item.deptId"
            :label="item.deptName"
            :value="item.deptId"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="楼宇号" prop="building">
        <el-input
          v-model="queryParams.building"
          placeholder="请输入楼宇号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <!-- <el-form-item label="房间号" prop="roomNumber">
        <el-input v-model="queryParams.roomNumber" placeholder="请输入房间号" clearable @keyup.enter.native="handleQuery" />
      </el-form-item> -->
      <el-form-item label="联系人姓名" prop="contactName">
        <el-input
          v-model="queryParams.contactName"
          placeholder="请输入联系人姓名"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="身份证号" prop="unit">
        <el-input
          v-model="queryParams.unit"
          placeholder="请输入身份证号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="联系电话" prop="contactPhone">
        <el-input
          v-model="queryParams.contactPhone"
          placeholder="请输入联系电话"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <!-- 1-- 2--移动 3--联通  4--其他 -->
      <el-form-item label="宽带运营商" prop="broadbandOperator">
        <el-select
          v-model="queryParams.broadbandOperator"
          placeholder="请选择宽带运营商"
          clearable
        >
          <el-option
            v-for="dict in dict.type.broadband_operators"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <!-- <el-form-item label="创建人ID" prop="createUserId">
        <el-input
          v-model="queryParams.createUserId"
          placeholder="请输入创建人ID"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item> -->
      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
          >重置</el-button
        >
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:info:add']"
          >新增</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:info:edit']"
          >修改</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:info:remove']"
          >删除</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['system:info:export']"
          >导出</el-button
        >
      </el-col>
      <right-toolbar
        :showSearch.sync="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <el-table
      v-loading="loading"
      :data="infoList"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column
        label="住户ID"
        align="center"
        prop="id"
        v-if="columns[0].visible"
      />
      <el-table-column label="所属部门" align="center" prop="deptId">
        <template slot-scope="scope">
          {{ getDeptName(scope.row.deptId) }}
        </template>
      </el-table-column>
      <el-table-column
        label="小区名称"
        align="center"
        prop="community"
        :show-overflow-tooltip="true"
      >
        <template slot-scope="scope">
          {{ getDeptName(scope.row.community) }}
        </template>
      </el-table-column>
      <el-table-column label="楼宇号" align="center" prop="building" />

      <el-table-column label="房间号" align="center" prop="roomNumber" />
      <el-table-column label="联系人姓名" align="center" prop="contactName" />
      <el-table-column label="身份证号" align="center" prop="unit" />
      <el-table-column label="联系电话" align="center" prop="contactPhone" />
      <el-table-column
        label="宽带运营商"
        align="center"
        prop="broadbandOperator"
      >
        <template slot-scope="scope">
          <dict-tag
            :options="dict.type.broadband_operators"
            :value="scope.row.broadbandOperator"
          />
        </template>
      </el-table-column>
      <!-- 状态：1-正常，0-删除 -->
      <!-- <el-table-column label="状态" align="center" prop="status">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.sys_normal_disable" :value="scope.row.status" />
        </template>
      </el-table-column> -->
      <!-- <el-table-column label="创建人ID" align="center" prop="createUserId" /> -->
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:info:edit']"
            >修改</el-button
          >
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:info:remove']"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改小区住户信息对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="800px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="92px">
        <el-row :gutter="20">
          <el-col :span="12">
            <!-- <el-form-item label="所属部门" prop="deptId"> -->
            <!-- <el-input v-model="form.deptId" placeholder="请输入所属部门" /> -->
            <!-- <el-select v-model="form.deptId" placeholder="请选择所属部门" clearable>
                <el-option v-for="item in deptList" :key="item.deptId" :label="item.deptName" :value="item.deptId" />
              </el-select> -->
            <el-form-item label="所属部门" prop="deptId">
              <!-- <treeselect v-model="form.deptId" :options="enabledDeptOptions" :show-count="true"
                placeholder="请选择小区名称" /> -->
              <el-cascader
                v-model="form.deptId"
                :options="deptOptions"
                @change="handleChange"
                placeholder="请选择所属部门"
              >
              </el-cascader>
            </el-form-item>
            <!-- </el-form-item> -->
          </el-col>
          <el-col :span="12">
            <el-form-item label="小区名称" prop="community">
              <!-- <el-input v-model="form.community" placeholder="请输入小区名称" /> -->
              <el-select
                v-model="form.community"
                placeholder="请先选择所属部门"
                clearable
              >
                <el-option
                  v-for="item in communityOptions"
                  :key="item.deptId"
                  :label="item.deptName"
                  :value="item.deptId"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="楼宇号" prop="building">
              <el-input
                v-model="form.building"
                placeholder="请输入楼宇号 如:1-2"
              />
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="房间号" prop="roomNumber">
              <el-input v-model="form.roomNumber" placeholder="请输入房间号" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="联系人姓名" prop="contactName">
              <el-input
                v-model="form.contactName"
                placeholder="请输入联系人姓名"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="身份证号" prop="unit">
              <el-input v-model="form.unit" placeholder="请输入身份证号" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="联系电话" prop="contactPhone">
              <el-input
                v-model="form.contactPhone"
                placeholder="请输入联系电话"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="宽带运营商" prop="broadbandOperator">
              <el-select
                v-model="form.broadbandOperator"
                placeholder="请选择宽带运营商"
              >
                <el-option
                  v-for="dict in dict.type.broadband_operators"
                  :key="dict.value"
                  :label="dict.label"
                  :value="parseInt(dict.value)"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>

          <!-- <el-form-item label="创建人ID" prop="createUserId">
          <el-input v-model="form.createUserId" placeholder="请输入创建人ID" />
        </el-form-item> -->
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listDept, listDeptExcludeChild, getDept } from "@/api/system/dept";
import { getDeptTree } from "@/api/system/user";
import {
  listInfo,
  getInfo,
  delInfo,
  addInfo,
  updateInfo,
} from "@/api/system/info";
import store from "@/store";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
export default {
  name: "Info",
  dicts: ["broadband_operators", "sys_normal_disable"],
  components: { Treeselect },
  data() {
    return {
      deptId: store.state.user.deptId, //将缓存的用户id赋值给deptId，用于查询所属部门
      // 过滤掉已禁用部门树选项
      communityOptions: [],
      deptId: [],
      deptOptions: [],
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 小区住户信息表格数据
      infoList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        deptId: null,
        community: null,
        building: null,
        unit: null,
        roomNumber: null,
        contactName: null,
        contactPhone: null,
        broadbandOperator: null,
        status: null,
        createUserId: null,
      },
      deptList: [],
      // 表单参数
      form: {},

      // 列信息
      columns: [{ key: 0, label: `住户ID`, visible: false }],
      // 表单校验
      rules: {
        deptId: [
          { required: true, message: "所属部门不能为空", trigger: "blur" },
        ],
        community: [
          { required: true, message: "小区名称不能为空", trigger: "blur" },
        ],
        building: [
          { required: true, message: "楼宇号不能为空", trigger: "blur" },
        ],
        unit: [
          { required: true, message: "身份证号不能为空", trigger: "blur" },
        ],
        roomNumber: [
          { required: true, message: "房间号不能为空", trigger: "blur" },
        ],
        contactName: [
          { required: true, message: "联系人姓名不能为空", trigger: "blur" },
        ],
        contactPhone: [
          { required: true, message: "联系电话不能为空", trigger: "blur" },
        ],
        broadbandOperator: [
          { required: true, message: "宽带运营商不能为空", trigger: "blur" },
        ],
      },
    };
  },
  created() {
    this.getList();
    this.getDeptList();
    this.getDeptTree(100);
  },
  mounted() {},
  methods: {
    lazyLoad(node, resolve) {
      console.log(node, "nodenode"); // 定义懒加载函数，根据需要从服务器获取数据并调用 resolve() 函数返回数据。这里仅为示例，实际应用中需要根据实际情况调整。
      if (node.level === 1) {
        // 第一级节点，加载第一级数据示例（实际应用中应从服务器获取）
        resolve([
          { value: "option1", label: "Option 1", isLeaf: false },
          { value: "option2", label: "Option 2", isLeaf: false },
        ]);
      }
    },
    /** 查询部门下拉树结构 */
    async getDeptTree(deptId) {
      getDeptTree({ deptId: deptId }).then((response) => {
        if (deptId == 100) {
          var treeData = response.data.children;
          treeData.map((item) => {
            item.label = item.deptName;
            item.value = item.deptId;
            if (item.children && item.children.length) {
              item.children.forEach((child) => {
                child.label = child.deptName;
                child.value = child.deptId;
                delete child.children;
              });
            }
          });
          this.deptOptions = treeData;
        } else {
          var communityData = response.data.children;
          console.log(communityData, "communityDatacommunityData");
          this.communityOptions = communityData;
        }
      });
    },
    handleChange(value) {
      this.communityOptions = [];
      console.log(value, "value");
      console.log(value[1], "value");
      this.form.deptId = value[1];
      this.getDeptTree(value[1]);
    },
    getDeptList() {
      listDept().then((response) => {
        this.deptList = response.data;
        this.deptList = this.filterDisabledDept(this.deptList);
      });
    },

    // 过滤禁用的部门
    filterDisabledDept(deptList) {
      return deptList.filter((dept) => {
        if (dept.disabled) {
          return false;
        }
        if (dept.children && dept.children.length) {
          dept.children = this.filterDisabledDept(dept.children);
        }
        return true;
      });
    },
    getDeptName(deptId) {
      // this.getDeptDetail(deptId);
      return this.deptList.find((item) => item.deptId == deptId)?.deptName;
      // getDept(deptId).then((response) => {
      //   console.log(response.data.deptName)
      //   return response.data.deptName;
      // });
    },
    // getDeptDetail(deptId) {
    //   getDept(deptId).then((response) => {
    //     console.log(response)
    //   });
    // },
    /** 获取部门列表 */
    /** 查询小区住户信息列表 */
    getList() {
      this.loading = true;
      listInfo(this.queryParams).then((response) => {
        this.infoList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        deptId: null,
        community: null,
        building: null,
        unit: null,
        roomNumber: null,
        contactName: null,
        contactPhone: null,
        broadbandOperator: null,
        status: null,
        createUserId: null,
        createTime: null,
        updateTime: null,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.loading = true;
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加小区住户信息";
      this.deptOptions = [];
      this.communityOptions = [];
      this.getDeptTree(100);
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids;
      getInfo(id).then((response) => {
        this.form = response.data;
        this.open = true;
        this.title = "修改小区住户信息";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.form.id != null) {
            updateInfo(this.form).then((response) => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addInfo(this.form).then((response) => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
     
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal
        .confirm('是否确认删除小区住户信息编号为"' + ids + '"的数据项？')
        .then(function () {
          return delInfo(ids);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        "system/info/export",
        {
          ...this.queryParams,
        },
        `info_${new Date().getTime()}.xlsx`
      );
    },
  },
};
</script>
